package org.androidpn.server.service.impl;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.androidpn.server.dao.RoleDao;
import org.androidpn.server.dao.RoomDao;
import org.androidpn.server.entity.Role;
import org.androidpn.server.entity.Room;
import org.androidpn.server.entity.Room.RoomStatus;
import org.androidpn.server.service.RoomService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * service 角色
 * 
 * @author 蔡琪
 * 
 */
@Service("roomService")
public class RoomServiceImpl extends BaseServiceImpl<Room, Long> implements
		RoomService {

	@Resource(name = "roomDao")
	private RoomDao roomDao;

	@Resource(name = "roleDao")
	private RoleDao roleDao;

	@Resource(name = "roomDao")
	private void setBaseDao(RoomDao roomDao) {
		super.setBaseDao(roomDao);
	}

	@Transactional(readOnly = true)
	public List<Room> getOnlineRooms() {
		return roomDao.getOnlineRooms();
	}

	@Transactional
	public void createRoom(Room room) {
		room.setId(null);
		room.setStatus(RoomStatus.waitting);
		roomDao.persist(room);
		Set<Role> roles = room.getRoles();
		for (Role role : roles) {
			role = roleDao.getRoleByNickname(role.getNickname());
			role.setRoom(room);
			Set<Room> rooms = role.getRooms();
			rooms.add(room);
			room.setHost(role);
			roleDao.merge(role);
			roleDao.flush();
		}
		roomDao.merge(room);
	}

	@Transactional
	public Room joinRoom(Long roleID, Long roomID) {
		Room room = roomDao.find(roomID);
		Role role = roleDao.find(roleID);
		role.setRoom(room);
		role.setIsReady(false);
		room.getRoles().add(role);
		return roomDao.merge(room);
	}

	@Transactional
	public void quitRoom(Long roleID, Long roomID) {
		Room room = roomDao.find(roomID);
		Role role = roleDao.find(roleID);
		role.setRoom(null);
		role.setRooms(null);
		role.setIsReady(false);
		roleDao.merge(role);
		roleDao.flush();
		room.getRoles().remove(role);
		if (role.getId().equals(room.getHost().getId())) {
			room.setHost(null);
		}
		roomDao.merge(room);
		roomDao.flush();
	}

	@Transactional
	public void closeRoom(Long id) {
		Room room = roomDao.find(id);
		for (Role role : room.getRoles()) {
			quitRoom(role.getId(), room.getId());
		}
		roomDao.remove(roomDao.find(id));
	}

}
